<?php
/**
 * @Name 查询数据库表
 * @Description
 * @Auther 宋博
 * @Date 2021/5/18 10:50
 */

namespace Modules\SqlQeneratorApi\Http\service;


use Illuminate\Support\Facades\DB;
use Modules\Common\Services\CommonServices;
class QueryAataTablesService extends CommonServices
{
    /**
     * @Name  查询数据库表
     * @Description
     * @Author 宋博
     * @Date 2021/5/18 11:07
     * @Return Json
     */
    public function index(){
        $tables = DB::select("SHOW TABLE STATUS LIKE '" . config('database.connections.mysql')['prefix'] ."%'");
        $arr = [];
        foreach ($tables as $k => $v){
            //调用PHP格式化字节大小函数
            $arr[$k]['Name'] = $v->Name;//数据表名
            $arr[$k]['Rows'] = $v->Rows;//数据条数
            $arr[$k]['Engine'] = $v->Engine;//类型
            $arr[$k]['Collation'] = $v->Collation;//排序规则
            $arr[$k]['Create_time'] = $v->Create_time;//创建时间
            $arr[$k]['Comment'] = $v->Comment;//备注
            $arr[$k]['size'] = $this->format_bytes($v->Data_length);//占用空间
        }
        return $this->apiSuccess(['data'=>$arr]);
    }
    /**
     * @Name  PHP格式化字节大小
     * @Description
     * @Author 宋博
     * @Date 2021/5/18 13:15
     * @param   size  number    字节数
     * @param   delimiter string 数字和单位分隔符
     * @return string 格式化后的带单位的大小
     */
    private function format_bytes($size, $delimiter = '') {
        $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB');
        for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
        return round($size, 2) . $delimiter . $units[$i];
    }

}
